package server.proxy;

import server.storage.DiskOperations;
import server.unit.BlockingQueue;
import server.unit.Client;
import server.unit.Message;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;

public class MessagesSender extends Thread {
    private BlockingQueue<Message> queueMessages;
    private Map<String, List<Client>> lobbiesClients;
    private DiskOperations disk;
    private Lock read;

    public MessagesSender(Map<String, List<Client>> lobbiesClients, DiskOperations disk, Lock read) throws IOException {
        this.read = read;
        queueMessages = new BlockingQueue<>();
        this.lobbiesClients = lobbiesClients;
        this.disk = disk;
    }

    public void addMessage(Message message) {
        queueMessages.add(message);
    }

    @Override
    public void run() {
        while(!Thread.interrupted()) {
            Message message = queueMessages.remove();
            if(saveMessage(message)) {
                Client client;
                read.lock();
                List<Client> clientsList = lobbiesClients.get(message.getClient().getLobby());
                if(clientsList != null) {
                    for (Client aClientsList : clientsList) {
                        client = aClientsList;
                        client.write(message.toString());
                    }
                }
                read.unlock();
            }
        }
        disk.close();
    }

    private boolean saveMessage(Message message) {
        String answer;
        boolean result = disk.saveMessage(message.toString().substring(4).trim());
        if(result) {
            answer = "ACK OK";
        } else {
            answer = "ACK Message not saved";
        }
        message.getClient().write(answer);
        return result;
    }
}
